<template>
  <a-modal
    v-model:open="openForm"
    width="60vw"
    :title="`拉卡拉${props.rowData.productName ? '-' + props.rowData.productName : ''}`"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <a-form ref="formRef" :model="formData" v-bind="formOptions" :rules="props.formType == 'view' ? {} : rules" :disabled="props.formType == 'view'">
      <a-row :gutter="16">
        <a-col class="gutter-row" :span="24">
          <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">基本信息</group-title>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="商户注册类型:" :name="['jSubject', 'subjectType']">
            <a-radio-group v-model:value="jSubject.subjectType" name="radioGroup" :options="SUBJECT_TYPE_LAKALA" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="协议:" :name="['jSubject', 'agreeMent']">
            <a-upload
              v-model:file-list="jSubject.agreeMent"
              :max-count="1"
              name="agreeMent"
              :custom-request="(file) => uploadFunc(file, 'jSubject.agreeMent')"
              :accept="limitUpload['comment'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'agreeMent')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="24">
          <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">执照信息-法人身份证信息</group-title>
        </a-col>
        <template v-for="(item, index) in jIdentitiesList" :key="`${item?.userType}` - `${index}`">
          <template v-if="item?.userType == 1">
            <a-col class="gutter-row" :span="12">
              <a-form-item label="法人姓名:" :name="['jIdentitiesList', index, 'idDocName']">
                <a-input v-model:value="item.idDocName" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item label="身份证号码:" :name="['jIdentitiesList', index, 'idDocNumber']">
                <a-input v-model:value="item.idDocNumber" placeholder="请输入" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item label="身份证有效开始时间:" :name="['jIdentitiesList', index, 'idDocPeriodBegin']">
                <a-date-picker
                  class="w-full"
                  v-model:value="item.idDocPeriodBegin"
                  :disabled-date="(dataVal) => dataVal && item.idDocPeriodEnd && dataVal + 8.64e7 - 1000 >= new Date(item.idDocPeriodEnd).getTime()"
                  :valueFormat="'YYYY-MM-DD'"
                />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item label="身份证有效结束时间:" :name="['jIdentitiesList', index, 'idDocPeriodEnd']">
                <a-date-picker
                  class="w-full"
                  v-model:value="item.idDocPeriodEnd"
                  :disabled-date="(dataVal) => dataVal && item.idDocPeriodBegin && dataVal <= new Date(item.idDocPeriodBegin).getTime()"
                  :valueFormat="'YYYY-MM-DD'"
                />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item label="证件正面照片" :name="['jIdentitiesList', index, 'idDocCopy']">
                <a-upload
                  v-model:file-list="item.idDocCopy"
                  name="idDocCopy"
                  :max-count="1"
                  :custom-request="(file) => uploadFunc(file, `jIdentitiesList.${index}.idDocCopy`)"
                  :accept="limitUpload['comment'].fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'idDocCopy')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item label="证件反面照片:" :name="['jIdentitiesList', index, 'idDocCopyBack']">
                <a-upload
                  v-model:file-list="item.idDocCopyBack"
                  name="idDocCopyBack"
                  :max-count="1"
                  :custom-request="(file) => uploadFunc(file, `jIdentitiesList.${index}.idDocCopyBack`)"
                  :accept="limitUpload['comment'].fileType.toString()"
                  :before-upload="(file, fileList) => beforeUpload(file, fileList, 'idDocCopyBack')"
                  :headers="{
                    authorization: 'authorization-text',
                  }"
                >
                  <a-button>
                    <upload-outlined />
                    点击上传
                  </a-button>
                </a-upload>
              </a-form-item>
            </a-col>
          </template>
        </template>
        <template v-if="jSubject.subjectType == 5">
          <a-col class="gutter-row" :span="24">
            <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">执照信息-营业执照信息</group-title>
          </a-col>
          <a-col class="gutter-row" :span="12">
            <a-form-item label="营业执照名称:" :name="['jSubject', 'businessLicenseName']">
              <a-input v-model:value="jSubject.businessLicenseName" placeholder="请输入营业执照名称" />
            </a-form-item>
          </a-col>
          <a-col class="gutter-row" :span="12">
            <a-form-item label="营业执照号码:" :name="['jSubject', 'businessLicenseNo']">
              <a-input v-model:value="jSubject.businessLicenseNo" placeholder="请输入营业执照号码" />
            </a-form-item>
          </a-col>
          <a-col class="gutter-row" :span="12">
            <a-form-item label="执照有效开始时间:" :name="['jSubject', 'businessLicenseDtStart']">
              <a-date-picker
                class="w-full"
                v-model:value="jSubject.businessLicenseDtStart"
                :disabled-date="
                  (dataVal) =>
                    dataVal && jSubject.businessLicenseDtEnd && dataVal + 8.64e7 - 1000 >= new Date(jSubject.businessLicenseDtEnd).getTime()
                "
                :valueFormat="'YYYY-MM-DD'"
              />
            </a-form-item>
          </a-col>
          <a-col class="gutter-row" :span="12">
            <a-form-item label="执照有效结束时间:" :name="['jSubject', 'businessLicenseDtEnd']">
              <a-date-picker
                class="w-full"
                v-model:value="jSubject.businessLicenseDtEnd"
                :disabled-date="
                  (dataVal) => dataVal && jSubject.businessLicenseDtStart && dataVal <= new Date(jSubject.businessLicenseDtStart).getTime()
                "
                :valueFormat="'YYYY-MM-DD'"
              />
            </a-form-item>
          </a-col>
          <a-col class="gutter-row" :span="12">
            <a-form-item label="营业执照图片:" :name="['jSubject', 'businessLicensePic']">
              <a-upload
                v-model:file-list="jSubject.businessLicensePic"
                name="businessLicensePic"
                :max-count="1"
                :custom-request="(file) => uploadFunc(file, 'jSubject.businessLicensePic')"
                :accept="limitUpload['comment'].fileType.toString()"
                :before-upload="(file, fileList) => beforeUpload(file, fileList, 'businessLicensePic')"
                :headers="{
                  authorization: 'authorization-text',
                }"
              >
                <a-button>
                  <upload-outlined />
                  点击上传
                </a-button>
              </a-upload>
            </a-form-item>
          </a-col>
        </template>
      </a-row>

      <a-row :gutter="16">
        <a-col class="gutter-row" :span="24"> <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">商户信息</group-title></a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="商户注册名称:" :name="['jSubject', 'merchantShortName']">
            <a-input v-model:value="jSubject.merchantShortName" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="商户类别:" :name="['jSubject', 'mccCodeTwo']">
            <CustomSelect
              v-model:value="jSubject.mccCodeTwo"
              :placeholder="'请先选择商户类别'"
              :api="apiSource.businessPage"
              :queryParams="headParams"
              :initParams="headInitParams"
              @change="handleMccCode"
              queryParamKey="categoryName"
              value-field="categoryCode"
              label-field="categoryName"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="商户经营内容:" :name="['jSubject', 'businessContent']">
            <a-input v-model:value="jSubject.businessContent" showCount :maxlength="20" placeholder="请输入商户经营内容" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="商户经营名称:" :name="['jSubject', 'merName']">
            <a-input v-model:value="jSubject.merName" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="联系人姓名:" :name="['jSubject', 'name']">
            <a-input v-model:value="jSubject.name" placeholder="请输入联系人姓名" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="联系人手机号:" :name="['jSubject', 'phone']">
            <a-input v-model:value="jSubject.phone" placeholder="请输入联系人手机号" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="商户邮箱:" :name="['jSubject', 'email']">
            <a-input v-model:value="jSubject.email" placeholder="请输入邮箱" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col class="gutter-row" :span="24">
          <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">结算信息</group-title>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="结算人银行卡号:" :name="['jBankAccounts', 'accountNumber']">
            <a-input v-model:value="jBankAccounts.accountNumber" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="结算账户名称:" :name="['jBankAccounts', 'accountName']">
            <a-input v-model:value="jBankAccounts.accountName" placeholder="请输入" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="6">
          <a-form-item label="结算信息省份:" :name="['jBankAccounts', 'settleProvinceName']">
            <CustomSelect
              style="width: 100%"
              ref="bankRef"
              v-model:value="jBankAccounts.settleProvinceName"
              :placeholder="'请选择'"
              :api="lakalaBankArea"
              @change="changeProvince"
              queryParamKey="nameLike"
              :valueField="'name'"
              :labelField="'name'"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="6">
          <a-form-item label="结算信息城市:" :name="['jBankAccounts', 'settleCityName']">
            <CustomSelect
              style="width: 100%"
              ref="bankRef"
              v-model:value="jBankAccounts.settleCityName"
              :placeholder="'请选择'"
              :api="lakalaBankArea"
              @change="changeCity"
              :queryParams="{ parentCode: jBankAccounts.settleProvinceCode }"
              :valueField="'name'"
              :labelField="'name'"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12" v-if="jBankAccounts.settleProvinceCode">
          <a-form-item label="开户行名称:" :name="['jBankAccounts', 'bankName']">
            <CustomSelect
              ref="branchRef"
              style="width: 100%"
              v-model:value="jBankAccounts.bankName"
              :placeholder="'请选择'"
              :api="lakalaBank"
              @change="changeBankName"
              :queryParams="{ areaCode: jBankAccounts.settleProvinceCode }"
              queryParamKey="bankName"
              :valueField="'branchBankName'"
              :labelField="'branchBankName'"
            />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="开户行号:" :name="['jBankAccounts', 'bankBranchId']">
            <a-input v-model:value="jBankAccounts.bankBranchId" disabled :placeholder="'开户行号'" />
            <!-- <CustomSelect
              ref="branchRef"
              style="width: 100%"
              v-model:value="jBankAccounts.bankBranchId"
              :placeholder="'请选择'"
              :api="lakalaBank"
              queryParamKey="branchBankNo"
              :valueField="'branchBankNo'"
              :labelField="'branchBankNo'"
            /> -->
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="清算行号:" :name="['jBankAccounts', 'clearingBankCode']">
            <a-input v-model:value="jBankAccounts.clearingBankCode" disabled :placeholder="'清算行号'" />
            <!-- <CustomSelect
              ref="branchRef"
              style="width: 100%"
              v-model:value="jBankAccounts.clearingBankCode"
              :placeholder="'请选择'"
              :api="lakalaBank"
              queryParamKey="clearNo"
              :valueField="'clearNo'"
              :labelField="'clearNo'"
            /> -->
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="6">
          <a-form-item label="结算方式:" :name="['jSubject', 'settlementType']">
            <template #tooltip>
              <a-tooltip placement="top">
                <template #title>
                  <div>
                    <div>手动结算：结算至拉卡拉APP钱包，需商户手动提现到银行</div>
                    <div>自动结算：交易资金自动结算到商户入网结算银行卡</div>
                    <div>定时结算：仅企业商户支持（结算时间点选择后，会按照所选时间段把商户待结算的资金全部结算至结算卡内。）</div>
                  </div>
                </template>
                <QuestionCircleOutlined />
              </a-tooltip>
            </template>
            <a-select v-model:value="jSubject.settlementType" :options="SETTLEMENT_TYPE_LAKALA" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="6" v-if="jSubject.settlementType == 'REGULAR'">
          <a-form-item label="定时结算时间:" :name="['jSubject', 'regularSettlementTime']">
            <template #tooltip>
              <a-tooltip placement="top">
                <template #title>
                  <div>
                    <div>结算时段间隔周期为每整点1小时</div>
                    <div>结算时间点选择后,会按照所选时间段把商户待结算资金的全部结算至结算卡内;</div>
                    <div>例:若选择19点结算,该商户19点前未结算交易将在19点后结算到结算卡内;</div>
                  </div>
                </template>
                <QuestionCircleOutlined />
              </a-tooltip>
            </template>
            <a-time-picker v-model:value="jSubject.regularSettlementTime" value-format="HHmm" format="HHmm" placeholder="请选择" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="24">
          <a-form-item label="结算周期:" :name="['jSubject', 'settleType']">
            <a-radio-group v-model:value="jSubject.settleType" name="radioGroup" :options="SETTLE_TYPE_LAKALA" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="银行卡正面照:" :name="['jSubject', 'bankCard']">
            <a-upload
              v-model:file-list="jSubject.bankCard"
              :max-count="1"
              name="bankCard"
              :custom-request="(file) => uploadFunc(file, 'jSubject.bankCard')"
              :accept="limitUpload['comment'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'bankCard')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12" v-if="jSubject.subjectType == '5'">
          <a-form-item label="开户许可证:" :name="['jSubject', 'openingPermit']">
            <a-upload
              v-model:file-list="jSubject.openingPermit"
              :max-count="1"
              name="openingPermit"
              :custom-request="(file) => uploadFunc(file, 'jSubject.openingPermit')"
              :accept="limitUpload['comment'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'openingPermit')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row :gutter="16">
        <a-col class="gutter-row" :span="24">
          <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">费率信息</group-title>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="线上成本价:">
            <a-input v-model:value="rateF.onlineRate" disabled placeholder="线上成本价" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="线下成本价:">
            <a-input v-model:value="rateF.offlineRate" disabled placeholder="线下成本价" />
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="24">
          <a-form-item label="微信/支付宝费率:" :name="['jSubject', 'rate']" help="设置费率在成本价到0.6%之间">
            <a-input v-model:value="jSubject.rate" placeholder="请输入费率" />
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col class="gutter-row" :span="24">
          <group-title class="pb-0.5" :iconOptions="{ class: 'text-blue-400' }">门店信息</group-title>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="门头照:" :name="['jSubject', 'shopOutsideImg']">
            <a-upload
              v-model:file-list="jSubject.shopOutsideImg"
              :max-count="1"
              name="shopOutsideImg"
              :custom-request="(file) => uploadFunc(file, 'jSubject.shopOutsideImg')"
              :accept="limitUpload['comment'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'shopOutsideImg')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="商铺内部照片:" :name="['jSubject', 'shopInsideImg']">
            <a-upload
              v-model:file-list="jSubject.shopInsideImg"
              :max-count="1"
              name="shopInsideImg"
              :custom-request="(file) => uploadFunc(file, 'jSubject.shopInsideImg')"
              :accept="limitUpload['comment'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'shopInsideImg')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
        <a-col class="gutter-row" :span="12">
          <a-form-item label="收银台照:" :name="['jSubject', 'checkstandImg']">
            <a-upload
              v-model:file-list="jSubject.checkstandImg"
              :max-count="1"
              name="checkstandImg"
              :custom-request="(file) => uploadFunc(file, 'jSubject.checkstandImg')"
              :accept="limitUpload['comment'].fileType.toString()"
              :before-upload="(file, fileList) => beforeUpload(file, fileList, 'checkstandImg')"
              :headers="{
                authorization: 'authorization-text',
              }"
            >
              <a-button>
                <upload-outlined />
                点击上传
              </a-button>
            </a-upload>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <template #footer>
      <div v-if="props.formType != 'view'">
        <a-button @click="handleCancel"> 取消 </a-button>
        <a-button @click="getHistoryData"> 调用进件资料 </a-button>
        <a-button @click="handleSave"> 保存 </a-button>
        <a-button type="primary" @click="handleOk"> 提交 </a-button>
      </div>
    </template>
  </a-modal>
</template>
<script setup name="AlipayForm">
  import { computed, onMounted, reactive, ref, watch, toRefs } from 'vue'
  import { message, Upload } from 'ant-design-vue'
  import { SmartLoading } from '/@/components/framework/smart-loading'
  import CustomSelect from '/@/components/business/comment/CustomSelect.vue'
  import { registApi } from '/@/api/business/b-operation/regist/index.js'
  import { registApi as agentRegistApi } from '/@/api/business/b-agent/regist/index.js'
  import { businessApi } from '/@/api/business/b-operation/regist/business.js'
  import { businessApi as agentBusinessApi } from '/@/api/business/b-agent/regist/business.js'
  import { lakalaBank, lakalaBankArea } from '/@/api/business/b-agent/bank/bank-api.js'
  import { merchantApi } from '/@/api/business/b-agent/merchant/merchant-api'
  import { getRate as agentGetRate } from '/@/api/business/b-agent/channel/pay-config-api'
  import { getRate } from '/@/api/business/b-operation/agent/agent-payconfig-api'
  import { cloneDeep, isEmpty } from 'lodash'
  import { getObjValue, setObjValue, modifyFields, strToArr } from '/@/utils/common.js'
  import { myUpload } from '/@/utils/myUpload'
  import { isNum, validatePhoneNot } from '/@/utils/validate'
  import {
    SUBJECT_TYPE_LAKALA, //应用市场
    SETTLEMENT_TYPE_LAKALA, //结算方式
    SETTLE_TYPE_LAKALA, //结算类型
  } from '/@/constants/dict'

  import { useUserStore } from '/@/store/modules/system/user'
  const USER_TYPE = useUserStore().userType // 用户类型: 1-平台;2-代理;4-商户

  const apiSource = {
    businessPage: (data) => {
      if (USER_TYPE == '2') return agentBusinessApi.page(data)
      if (USER_TYPE == '1') return businessApi.page(data)
    },
    detailPage: (data) => {
      if (USER_TYPE == '2') return agentRegistApi.detailPage(data)
      if (USER_TYPE == '1') return registApi.detailPage(data)
    },
    findId: (data) => {
      if (USER_TYPE == '2') return agentRegistApi.findId(data)
      if (USER_TYPE == '1') return registApi.findId(data)
    },
    save: (data) => {
      if (USER_TYPE == '2') return agentRegistApi.save(data)
      if (USER_TYPE == '1') return registApi.save(data)
    },
    submit: (data) => {
      if (USER_TYPE == '2') return agentRegistApi.submit(data)
      if (USER_TYPE == '1') return registApi.submit(data)
    },
    findIdByChannelType: (data) => {
      if (USER_TYPE == '2') return agentRegistApi.findIdByChannelType(data)
      if (USER_TYPE == '1') return registApi.findIdByChannelType(data)
    },
    getRate: (data) => {
      if (USER_TYPE == '2') return agentGetRate(data)
      if (USER_TYPE == '1') return getRate(data)
    },
  }

  const props = defineProps({
    open: {
      type: Boolean,
      default: false,
    },
    rowData: {
      type: Object,
      default: () => {
        return {
          id: '', //商户进件详情id(mpdId)
          channelType: '',
          apiType: '', //产品类型
        }
      },
    },
    // 表单类型 add/update/view
    // add: 新增, update: 编辑,view: 查看
    formType: {
      type: String,
      default: 'add',
    },
    formOptions: {
      type: Object,
      default: () => {
        return {
          layout: 'vertical',
          name: 'basic',
          autocomplete: 'off',
        }
      },
    },
    params: {
      type: Object,
      default: () => {
        return {}
      },
    },
  })

  const emit = defineEmits(['update:open', 'ok'])
  const openForm = computed({ get: () => props.open, set: (val) => emit('update:open', val) })

  const alipayType = {
    0: '通用',
    1: '当面付',
  }

  // 图片字段
  const imgField = [
    'specialQualifications',
    'qualifications',
    'businessLicensePic',
    'financeLicensePics',
    'businessLicenseAuthPic',
    'indexUrl',
    'remarkUrl',
    'payUrl',
    'authorizationUrl',
    'productUrl',
    'idDocCopy',
    'idDocCopyBack',
    'authorizeLetterCopy',
    'businessAuthorizationLetter',
    'legalPersonCommitment',
    'legalPersonVideo',
    'businessAdditionPics',
    'agreeMent',
    'bankCard',
    'openingPermit',
    'shopOutsideImg',
    'shopInsideImg',
    'checkstandImg',
  ]
  // 商户身份信息子表字段
  const jIdentitiesListChild = {
    idHolderType: undefined, //证件持有人类型（LEGAL：经营者/法人；SUPER：经办人）
    idDocType: undefined, //证件类型: 0: 中国大陆居民-身份证 1: 其他国家或地区居民-护照 2: 中国香港居民-来往内地通行证 3: 中国澳门居民-来往内地通行证 4: 中国台湾居民-来往大陆通行证 5: 外国人居留证 6: 港澳居民证 7: 台湾居民证
    idDocName: undefined, //证件姓名
    idDocNumber: undefined, //证件号码
    idDocAddress: undefined, //证件居住地址
    idDocPeriodBegin: undefined, //证件有效期开始时间
    idDocPeriodEnd: undefined, //证件有效期结束时间
    idDocLongTermFlag: undefined, //证件是否长期有效
    userType: undefined, //用户类型 0超级管理员 1经营者/法人 2最终受益人
    owner: undefined, //是否受益人 0否1是
    businessAuthorizationLetter: [], //业务办理授权函（仅当 contact_type= SUPER 时填写）
    authorizeLetterCopy: [], //法定代表人说明函
    idDocCopy: [], //证件正面照片
    idDocCopyBack: [], //证件反面照片
  }
  const initData = {
    mpdId: undefined, //商户进件关联编号
    jBankAccounts: {
      channelId: undefined, //通道id
      bankAccountType: undefined, //银行账户类型 0: 对公银行账户 1: 经营者个人银行卡
      accountName: undefined, //账户名称
      accountBank: undefined, //开户银行
      bankAddressCode: undefined, //银行地址编码
      bankBranchId: undefined, //银行支行ID
      bankName: undefined, //银行名称
      accountNumber: undefined, //银行账号
      needBankBranch: undefined, //是否需要支行
      clearingBankCode: undefined, //结算账户清算⾏号
      settleProvinceCode: undefined, //结算信息省份代码
      settleProvinceName: undefined, //结算信息省份名称
      settleCityCode: undefined, //结算信息城市代码
      settleCityName: undefined, //结算信息城市名称
      serviceType: undefined, //服务类型：1代收；2代付；3自动分账；4不分账
      auditStatus: undefined, //审核状态：1待审核；2审核中；3审核通过；4审核拒绝
      auditMsg: undefined, //审核原因
      settlementType: undefined, //结算方式：1银行卡；2支付宝账号
      outCode: undefined, //外部编号
      utime: undefined, //可选
    }, //结算银行账户表
    jSubject: {
      financeInstitution: undefined, //是否为金融机构 0否1是
      businessLicenseMobile: undefined, //营业执照法人手机号
      merchantShortName: undefined, //商户简称
      dateLimitation: undefined, //营业期限
      businessLicenseDtStart: undefined, //营业执照开始时间
      business_licenseDtEnd: undefined, //营业执照结束时间
      businessContent: undefined, //营业执照上的经营内容（拉卡拉20字以内）
      settleType: undefined, //结算类型：1 D0秒到；2 D1次日结算
      settlementType: undefined, //结算方式
      regularSettlementTime: undefined, //定时结算时间
      settlementId: undefined, //结算规则ID
      subjectType: undefined, //主体类型： 0: 营业执照上的主体类型一般为个体户、个体工商户、个体经营 1: 营业执照上的主体类型一般为有限公司、有限责任公司 2: 包括各级、各类政府机关，如机关党委、税务、民政、人社、工商、商务、市监等 3:包括国内各级、各类政府机构、事业单位等。 如：公安、党团、司法、交通、旅游、工商税务、市政、医疗、教育、学校等机构 4: 包括社会团体、民办非企业、基金会、基层群众性自治组织、农村集体经济组织等组织
      mccCode: undefined, //经营类目
      mccCodeOne: undefined, //经营类目
      mccCodeTwo: undefined, //经营类目
      activitiesAdditions: undefined, //活动附加说明 用,拼接
      qualificationType: undefined, //所属行业类型
      qualifications: [], //特殊资质说明 用,拼接
      signAndAuth: 1, //签约且授权标识，默认为false，只进行签约操作； 如果设置为true，则表示签约成功后，会自动进行应用授权操作。
      longTerm: 1, //营业执照是否长期有效 0否 1是
      activitiesId: undefined, //活动ID
      merchantId: undefined, //自定义商户编号
      rate: undefined, //服务费率（%），0.38~0.6 之间（小数点后两位，可取0.38%及0.6%）。 当签约且授权标识 sign_and_auth=true 时，该费率信息必填
      activitiesRate: undefined, //活动费率
      legalPersonVideo: undefined, //法人开户意愿视频 1、建议法人按如下话术录制“法人开户意愿视频”： 我是#公司全称#的法定代表人（或负责人），特此证明本公司申请的商户号为我司真实意愿开立且用于XX业务（或XX服务）。我司现有业务符合法律法规及腾讯的相关规定。 2、支持上传20M内的视频，格式可为avi、wmv、mpeg、mp4、mov、mkv、flv、f4v、m4v、rmvb； 3、请填写通过视频上传API预先上传视频生成好的MediaID 。
      id: undefined, //编号
      debitActivitiesRate: undefined, //借记卡活动费率
      creditActivitiesRate: undefined, //信用卡活动费率
      legalPersonCommitment: undefined, //法人开户承诺函1、请上传法定代表人或负责人亲笔签署的开户承诺函扫描件（下载模板）。亲笔签名承诺函内容清晰可见，不得有涂污，破损，字迹不清晰现象； 2、请填写通过图片上传API预先上传图片生成好的MediaID
      email: undefined, //邮箱
      specialLicenseType: undefined, //特殊资质类型
      certificateLetterCopy: undefined, //单位证明函照片
      businessLicenseAddress: undefined, //营业执照的注册地址，若该字段未填写，系统将会查询国家工商信息填入。需注意若工商信息查询不到，则会被审核驳回。
      servicePhone: undefined, //服务电话
      businessAdditionMsg: undefined, //补充说明
      businessLicenseName: undefined, //营业执照商户名称
      businessLicenseNo: undefined, //营业执照号码
      businessAdditionPics: undefined, //补充材料 1、最多可上传5张照片； 2、请填写通过图片上传API预先上传图片生成好的MediaID。
      phone: undefined, //手机号
      name: undefined, //姓名
      financeType: undefined, //金融机构类型 为金融机构时必传
      storeInfo: undefined, //销售场景
      account: undefined, //支付宝账号
      specialQualifications: [], //企业特殊资质图片
      agreeMent: [], //协议照片
      bankCard: [], //银行卡照片
      openingPermit: [], //开店许可证图片
      shopOutsideImg: [], //门头照
      shopInsideImg: [], //店铺内照
      checkstandImg: [], //收银台照
      businessLicensePic: [], //营业执照图片
      financeLicensePics: [], //金融机构许可证图片 用,拼接
      businessLicenseAuthPic: [], //营业执照授权函
    }, //商户经营信息表出参
    apiType: 1, //接口类型 0通用 1当面付
    jIdentitiesList: [], //商户身份信息
    sceneTypeArr: [], //场景类型
  }
  const formData = reactive(cloneDeep(initData))
  const { jBankAccounts, jSubject, jIdentitiesList } = toRefs(formData)

  const rules = ref({
    sceneTypeArr: [{ required: true, message: '交易场景 不能为空!', trigger: ['blur', 'change'] }], //交易场景
    jSubject: {
      account: [{ required: true, message: '商户号/支付宝账号不能为空!' }],
      name: [{ required: true, message: '姓名不能为空!' }],
      phone: [
        { required: true, message: '手机号码不能为空!' },
        {
          validator: validatePhoneNot,
        },
      ],
      email: [{ required: true, message: '商户邮箱 不能为空!', trigger: ['blur', 'change'] }],
      businessLicenseName: [{ required: true, message: '营业执照名称 不能为空!', trigger: ['blur', 'change'] }],
      subjectType: [{ required: true, message: '主体类型 不能为空!', trigger: ['blur', 'change'] }],
      businessLicenseDtStart: [{ required: true, message: '营业执照开始时间 不能为空!', trigger: ['blur', 'change'] }],
      businessLicenseDtEnd: [{ required: true, message: '营业执照结束时间 不能为空!', trigger: ['blur', 'change'] }],
      merchantShortName: [{ required: true, message: '商户注册名称 不能为空!', trigger: ['blur', 'change'] }],
      mccCodeOne: [{ required: true, message: '经营类目 不能为空!', trigger: ['blur', 'change'] }],
      businessContent: [{ required: true, message: ' 营业执照上的经营内容 不能为空!', trigger: ['blur', 'change'] }],
      merName: [{ required: true, message: ' 商户经营名称 不能为空!', trigger: ['blur', 'change'] }],
      settleType: [{ required: true, message: '结算类型 不能为空!', trigger: ['blur', 'change'] }],
      settlementType: [{ required: true, message: '结算方式 不能为空!', trigger: ['blur', 'change'] }],
      regularSettlementTime: [{ required: true, message: '定时结算时间 不能为空!', trigger: ['blur', 'change'] }],
      mccCodeTwo: [{ required: true, message: '经营类目 不能为空!', trigger: ['blur', 'change'] }],
      rate: [{ required: true, message: '费率 不能为空!', trigger: ['blur', 'change'] }],
      specialQualifications: [
        {
          required: computed(() => {
            return jSubject.value.specialLicenseType == '1'
          }),
          message: '企业特殊资质图片 不能为空!',
          trigger: ['blur', 'change'],
        },
      ],
      agreeMent: [
        {
          required: true,
          message: '协议照片 不能为空!',
          trigger: ['blur', 'change'],
        },
      ],
      bankCard: [
        {
          required: true,
          message: '银行卡照片 不能为空!',
          trigger: ['blur', 'change'],
        },
      ],
      openingPermit: [
        {
          required: true,
          message: '开店许可证照片 不能为空!',
          trigger: ['blur', 'change'],
        },
      ],
      shopOutsideImg: [
        {
          required: true,
          message: '门头照 不能为空!',
          trigger: ['blur', 'change'],
        },
      ],
      shopInsideImg: [
        {
          required: true,
          message: '店铺内照 不能为空!',
          trigger: ['blur', 'change'],
        },
      ],
      checkstandImg: [
        {
          required: true,
          message: '收银台照 不能为空!',
          trigger: ['blur', 'change'],
        },
      ],
      businessLicenseNo: [{ required: true, message: '营业执照号码 不能为空!', trigger: ['blur', 'change'] }],
      businessLicenseMobile: [{ required: true, message: '营业执照法人手机号 不能为空!', trigger: ['blur', 'change'] }],
      longTerm: [{ required: true, message: '营业期限是否长期有效 不能为空!', trigger: ['blur', 'change'] }],
      businessLicensePic: [
        {
          required: true,
          message: '营业执照图片 不能为空!',
          trigger: ['blur', 'change'],
        },
      ],
    },

    jIdentitiesList: computed(() => {
      let arr = []
      if (jIdentitiesList.value && jIdentitiesList.value.length > 0) {
        jIdentitiesList.value.forEach((item) => {
          arr.push({
            idHolderType: [{ required: true, message: '证件持有人类型 不能为空!', trigger: ['blur', 'change'] }],
            idDocType: [
              {
                required:
                  (item.userType == '0' && item.idHolderType == 'SUPER') ||
                  (item.userType == '1' && item.idHolderType == 'LEGAL') ||
                  item.userType == '2',
                message: '证件类型 不能为空!',
                trigger: ['blur', 'change'],
              },
            ],
            idDocName: [{ required: true, message: '证件姓名 不能为空!', trigger: ['blur', 'change'] }],
            idDocNumber: [
              {
                required: (item.userType == '0' && item.idHolderType == 'SUPER') || item.userType != '0',
                message: '证件号码 不能为空!',
                trigger: ['blur', 'change'],
              },
            ],
            idDocAddress: [
              {
                required: (item.userType == '1' && jSubject.value.subjectType == '1') || item.userType != '1',
                message: '证件居住地址 不能为空!',
                trigger: ['blur', 'change'],
              },
            ],
            idDocPeriodBegin: [
              {
                required: (item.userType == '0' && item.idHolderType == 'SUPER') || item.userType != '0',
                message: '证件有效期开始时间 不能为空!',
                trigger: ['blur', 'change'],
              },
            ],
            idDocPeriodEnd: [
              {
                required: (item.userType == '0' && item.idHolderType == 'SUPER') || item.userType != '0',
                message: '证件有效期结束时间 不能为空!',
                trigger: ['blur', 'change'],
              },
            ],
            idDocLongTermFlag: [{ required: true, message: '证件是否长期有效 不能为空!', trigger: ['blur', 'change'] }],
            userType: [{ required: true, message: '用户类型 不能为空!', trigger: ['blur', 'change'] }],
            owner: [
              { required: item.userType == '1' && jSubject.value.subjectType == '1', message: '是否受益人 不能为空!', trigger: ['blur', 'change'] },
            ],
            businessAuthorizationLetter: [
              { required: item.idHolderType == 'SUPER', message: '业务办理授权函 不能为空!', trigger: ['blur', 'change'] },
            ],
            authorizeLetterCopy: [{ required: item.idHolderType == 'SUPER', message: '法定代表人说明函 不能为空!', trigger: ['blur', 'change'] }],
            idDocCopy: [
              {
                required: (item.userType == '0' && item.idHolderType == 'SUPER') || item.userType != '0',
                message: '证件正面照片 不能为空!',
                trigger: ['blur', 'change'],
              },
            ],
            idDocCopyBack: [
              {
                required: (item.userType == '0' && item.idHolderType == 'SUPER') || item.userType != '0',
                message: '证件反面照片 不能为空!',
                trigger: ['blur', 'change'],
              },
            ],
          })
        })
      }
      return arr
    }),
    jBankAccounts: computed(() => {
      return {
        bankAccountType: [{ required: true, message: '账户类型 不能为空!', trigger: ['blur', 'change'] }],
        accountName: [{ required: true, message: '结算账户名称 不能为空!', trigger: ['blur', 'change'] }],
        accountBank: [{ required: true, message: '结算账户名称 不能为空!', trigger: ['blur', 'change'] }],
        bankAddressCode: [{ required: false, message: '开户行地区 不能为空!', trigger: ['blur', 'change'] }],
        bankBranchId: [{ required: true, message: '开户行号 不能为空!', trigger: ['blur', 'change'] }],
        settleProvinceCode: [{ required: true, message: '结算信息省份 不能为空!', trigger: ['blur', 'change'] }],
        clearingBankCode: [{ required: true, message: '结算账户清算⾏号 不能为空!', trigger: ['blur', 'change'] }],
        settleCityCode: [{ required: true, message: '结算信息城市 不能为空!', trigger: ['blur', 'change'] }],
        settleProvinceName: [{ required: true, message: '结算信息省份 不能为空!', trigger: ['blur', 'change'] }],
        settleCityName: [{ required: true, message: '结算信息城市 不能为空!', trigger: ['blur', 'change'] }],
        bankName: [{ required: true, message: '开户行名称 不能为空!', trigger: ['blur', 'change'] }],
        accountNumber: [{ required: true, message: '银行账号 不能为空!', trigger: ['blur', 'change'] }, { validator: isNum }],
      }
    }),
  })

  const formRef = ref()
  const limitUpload = {
    comment: {
      fileType: ['.jpg', '.jpeg', '.png', '.bmp', '.gif'],
      fileSize: 2,
    },
    legalPersonVideo: {
      fileType: ['.avi', '.wmv', '.mpeg', '.mp4', '.mov', '.mkv', '.flv', '.f4v', '.m4v', '.rmvb'],
      fileSize: 5,
    },
  }
  const beforeUpload = (file, fileList, type) => {
    // 校检文件类型
    if (limitUpload['comment'].fileType.length) {
      const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      const isTypeOk = limitUpload['comment'].fileType.includes(fileExt)
      if (!isTypeOk) {
        message.warning(`文件格式不正确, 请上传${limitUpload['comment'].fileType.toString().replace(/\./g, '').replace(/,/g, '、')}格式文件!`)
        return false || Upload.LIST_IGNORE
      }
    }

    // 校检文件大小
    if (limitUpload['comment'].fileSize) {
      const isLt = file.size / 1024 / 1024 < limitUpload['comment'].fileSize
      if (!isLt) {
        message.warning(`上传文件大小不能超过 ${limitUpload['comment'].fileSize} MB!`)
        return false || Upload.LIST_IGNORE
      }
    }

    return true
  }

  // 上传文件自定义的方法
  const uploadFunc = async (file, fieldName) => {
    // console.log('file==>', file)
    // 确保获取到文件对象
    const fileObj = file.file
    if (!fileObj) {
      return
    }
    const response = await myUpload(file)
    console.log('response==>', response)
    let arr = getObjValue(formData, fieldName).map((item) => {
      if (item.uid === fileObj.uid) {
        message.success(`${fileObj.name} 上传成功`)
        return response
      }
      return item
    })
    setObjValue(formData, fieldName, arr)
  }

  //校验表单
  const validateForm = async () => {
    let isValid = false
    try {
      await formRef.value.validate()
      isValid = true
    } catch (error) {
      message.warning(error.errorFields[0].errors)
      isValid = false
    }
    return isValid
  }

  //保存
  const handleSave = async () => {
    const param = { ...cloneDeep(formData), ...cloneDeep(props.params) }
    imgInit(param)
    if (props.formType != 'view') {
      try {
        let res = await apiSource.save(param)
        message.success('保存成功')
        emit('ok', formData)
        return res
      } catch (error) {
        console.error(error)
      }
    }
  }

  //提交
  const handleOk = () => {
    // open.value = false
    validateForm().then((isValid) => {
      if (isValid) {
        handleSave().then(() => {
          const param = { checkStatus: 0, id: props.rowData.id }
          apiSource.submit(param).then(() => {
            message.success('提交成功')
            resetForm()
            emit('ok', formData)
            openForm.value = false
          })
        })
      }
    })
  }

  const handleCancel = () => {
    openForm.value = false
    resetForm()
    // open.value = false
  }
  const resetForm = () => {
    // 重置表单的 UI 状态
    try {
      formRef.value.resetFields()
    } catch (error) {
      console.error(error)
    }
    // 重置表单数据
    Object.assign(formData, cloneDeep(initData))
  }

  let areaFieldArr = ['shopProvinceCode', 'shopCityCode', 'shopDistrictCode']
  // 地址拆分
  const changeArea = (val, data) => {
    val.forEach((item, index) => {
      data[areaFieldArr[index]] = item
    })
  }
  // 地址合并
  function mergeArea(data) {
    data.jSceneList.forEach((item) => {
      if (item.sceneType == '0') {
        for (let i = 0; i <= areaFieldArr.length; i++) {
          if (!item[areaFieldArr[i]]) {
            item.shopAddress1 = item[areaFieldArr[i - 1]]
          }
        }
      }
    })
  }

  //调用进件资料
  function getHistoryData() {
    SmartLoading.show()
    let p = { id: props.rowData.id, channelType: props.rowData.channelType }
    apiSource
      .findIdByChannelType(p)
      .then((res) => {
        // jSubject/jSceneList
        if (isEmpty(res?.data)) return
        let resData = res.data
        imgInit(resData)
        mergeArea(resData)
        Object.assign(formData, resData)
        initFormList()
      })
      .finally(() => {
        SmartLoading.hide()
      })
  }
  // 获取表单数据
  function getFormData(data) {
    SmartLoading.show()
    let p = { mpdId: data.id, type: data.channelType }
    apiSource
      .findId(p)
      .then((res) => {
        // jSubject/jSceneList
        let resData = res.data
        resData.mpdId = data.id
        imgInit(resData)
        mergeArea(resData)
        Object.assign(formData, resData)
        initFormList()
      })
      .catch((err) => {
        console.error(err)
        initFormList()
      })
      .finally(() => {
        SmartLoading.hide()
      })
  }
  // 图片初始化
  function imgInit(resData) {
    modifyFields(resData, imgField, (value, key) => {
      let val
      if (isEmpty(value)) return
      if (typeof value === 'string') {
        val = strToArr(value).map((item, index) => {
          return {
            uid: `db-file-${index}`,
            name: `${key}${index > 0 ? '_' + index : ''}`,
            status: 'done',
            url: item,
          }
        })
      }
      if (Array.isArray(value)) {
        val = value.map((e) => e.url).toString()
      }
      return val
    })
  }

  // 主体类型
  const headParams = computed(() => {
    return {
      channelType: 5,
    }
  })
  const headInitParams = computed(() => {
    return {
      categoryCode: jSubject.value.mccCodeTwo,
    }
  })
  //  切换商户类别
  const handleMccCode = (val, options) => {
    if (isEmpty(val)) {
      jSubject.value.mccCodeOne = ''
      return
    }

    jSubject.value.mccCodeOne = options[0].mccCode
  }

  // 切换开户行
  const changeBankName = (val, options) => {
    if (isEmpty(val)) {
      jBankAccounts.value.bankBranchId = ''
      jBankAccounts.value.clearingBankCode = ''
      return
    }
    jBankAccounts.value.bankBranchId = options[0].branchBankNo
    jBankAccounts.value.clearingBankCode = options[0].clearNo
  }

  // 结算信息省市
  const changeProvince = (val, options) => {
    console.log(val)
    if (isEmpty(val)) {
      jBankAccounts.value.settleProvinceName = ''
      jBankAccounts.value.settleProvinceCode = ''
      return
    }
    jBankAccounts.value.settleProvinceCode = options[0].code
  }
  const changeCity = (val, options) => {
    if (isEmpty(val)) {
      jBankAccounts.value.settleCityName = ''
      jBankAccounts.value.settleCityCode = ''
      return
    }
    jBankAccounts.value.settleCityCode = options[0].code
  }

  function show(data) {
    if (data && !isEmpty(data)) {
      // Object.assign(formData, data)
      getFormData(data)
    }
    console.log('show==>', data)
  }

  /* 数组表单初始化 */
  function initFormList() {
    // 必填人员处理
    formData.mpdId = formData?.mpdId ?? props.rowData?.id
    // 确保 jIdentitiesList 存在且是数组
    if (!Array.isArray(formData.jIdentitiesList)) {
      formData.jIdentitiesList = []
    }
    const requiredUserTypes = [1]
    // 一次性检查所需 userType 是否都存在
    const existingTypes = new Set(formData.jIdentitiesList.map((item) => item.userType))
    requiredUserTypes.forEach((userType) => {
      if (!existingTypes.has(userType)) {
        formData.jIdentitiesList.push({ ...cloneDeep(jIdentitiesListChild), userType })
      }
    })
  }

  // 获取成本价、代理费率
  const rateF = ref({
    onlineRate: undefined,
    offlineRate: undefined,
  })
  const getARate = async () => {
    console.log('props.rowData===>', props.rowData)

    const { productId, agentId, channelId } = props.rowData
    let params = { productId, agentId, channelId }

    const res = await apiSource.getRate(params)
    if (res.code === 200) {
      rateF.value = res.data
    }
    // console.log('111111=>>>>', rateF.value)
  }

  watch(
    [() => props.rowData, () => props.open, () => props.params],
    (newVal) => {
      // apiType 判断通用还是当面付
      formData.apiType = props.params?.apiType || props.rowData?.apiType
      if (props.open) {
        getARate()
      }
      if (props.rowData?.id) {
        formData.mpdId = props.rowData?.id
      }
      if ((props.formType == 'update' || props.formType == 'view') && props.open) {
        show(cloneDeep(newVal[0]))
      }
      if (props.formType == 'add' && props.open) {
        initFormList()
      }
    },
    { deep: true, immediate: true },
  )
  // watch([() => formData.sceneTypeArr], (newVal) => {}, { deep: true, immediate: true })
  // 在组件挂载时初始化地址选项
  onMounted(() => {})
  defineExpose({
    formRef,
  })
</script>
<style lang="scss" scoped></style>
